// import * as THREE from 'three'

/**
 * option
 * @param {*设置粒子大小} size
 * @param {*设置粒子是否透明} transparent
 * @param {*设置粒子是否近大远小} sizeAttenuation
 * @param {*粒子纹理图片} image
 * @param {*粒子运行速度} speed
 * @param {*粒子个数} particalNumber
 */
export default function WeatherParticle({
  size = 20,
  transparent = false,
  sizeAttenuation = true,
  image = null,
  speed = 0.5,
  particleNumber = 100000,
  position = {
    lon: 0,
    lat: 0,
    height: 0,
  },
  radius = 2500,
  threeEarth = null,
}) {
  this._size = size;
  this._transparent = transparent;
  this._sizeAttenuation = sizeAttenuation;
  if (image) {
    this._image = image;
  } else {
    throw new Error("请传入粒子纹理图片！");
  }

  this._speed = speed;
  this._particleNumber = particleNumber;

  this._radius = radius;

  if (threeEarth !== null && threeEarth instanceof PIETHREE.ThreeEarth) {
    this._threeEarth = threeEarth;
  } else {
    throw new Error("找不到threeEarth");
  }

  if (position && position.lon && position.lat && position.height) {
    this._lon = position.lon;
    this._lat = position.lat;
    this._height = position.height;
  } else {
    throw new Error("非后期处理模式下经纬度，高度缺一不可！");
  }
}

WeatherParticle.prototype.create = function () {
  const textureLoader = new THREE.TextureLoader();

  const sprite = textureLoader.load(this._image);

  var material = new THREE.PointsMaterial({
    size: this._size,
    map: sprite,
    transparent: this._transparent,
    blending: THREE.AdditiveBlending,
    depthTest: true,
    sizeAttenuation: this._sizeAttenuation,
  });

  const geom = new THREE.BufferGeometry();

  const vertices = [];
  for (let i = 0; i < this._particleNumber; i++) {
    const x = this._radius * (Math.random() * 2 - 1);
    const y = this._radius * (Math.random() * 2 - 1);
    const z = this._height * Math.random();
    vertices.push(x, y, z);
  }

  geom.setAttribute("position", new THREE.Float32BufferAttribute(vertices, 3));

  this._cloud = new THREE.Points(geom, material);

  this._cloud.name = "particles";

  this._cloudWorldMatrix = this._threeEarth.computeWorldMatrix(
    this._lon,
    this._lat,
    0
  );
  this._cloud.position.set(0, 0, 0);

  return this._cloud;
};

WeatherParticle.prototype.update = function () {
  //监听相机高度
  const positions = this._cloud.geometry.attributes.position.array;
  for (let i = 0; i < positions.length; i += 3) {
    if (positions[i + 2] < 0) {
      positions[i + 2] = this._height;
    } else {
      positions[i + 2] -= this._speed;
    }
  }
  this._cloud.geometry.attributes.position.needsUpdate = true;
  if (this._cloudWorldMatrix) {
    this._threeEarth.updateWorldMatrix(this._cloud, this._cloudWorldMatrix);
  }
};
